﻿// See https://aka.ms/new-console-template for more information
using System.Text.Json;
using System.Text;
using System.Runtime.Intrinsics.X86;
using MySql.Data.MySqlClient;

Console.WriteLine("Hello, World!");

var root = Directory.GetDirectories("D:\\wedo\\官方图纸");

foreach (var fs in root)
{
    var aDirectoryInfo = new DirectoryInfo(fs);
    var name = aDirectoryInfo.Name;
    //var introduction = "";
    var introduction = Getintroduction("用乐高搭建一个" + name + ",帮我写一句话的简介,不需要换行,内容在300字.语言适合8岁以内儿童.").Result;




    // 将HTML代码存储到字符串变量中
    string htmlIntroduction = $@"
<!-- wp:heading {{""level"":3}} -->
<h3 class=""wp-block-heading"">引言</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>{introduction}</p>
<!-- /wp:paragraph -->

";

    // 将 HTML 代码存储到字符串变量中
    string htmlStep = $@"
<!-- wp:heading {{""level"":3}} -->
<h3 class=""wp-block-heading"">搭建步骤</h3>
<!-- /wp:heading -->

";
    var HtmlPics = "";

    for (global::System.Int32 i = 0; i < aDirectoryInfo.GetFiles().Count(); i++)
    {

        // 定义 bks_pic 变量
        string bks_pic = $"https://www.legofuns.top/wp-content/uploads/wedo/官方图纸/{name}/{name}-{i + 1}.jpg";

        // 将 HTML 代码存储到字符串变量中
        string htmlPic = $@"
<!-- wp:image {{""id"":46,""sizeSlug"":""full"",""linkDestination"":""none""}} -->
<figure class=""wp-block-image size-full"">
    <img src=""{bks_pic}"" alt="""" class=""wp-image-46""/>
</figure>
<!-- /wp:image -->
";
        HtmlPics = HtmlPics + htmlPic;
    }


    // 定义 bks_summary 变量
    string bks_Tips = Getintroduction("写一段乐高搭建小技巧，300个字以内，只需要一段话，不要换行或者分段。").Result;

    // 将 HTML 代码存储到字符串变量中
    string htmlTips = $@"
<!-- wp:heading {{""level"":3}} -->
<h3 class=""wp-block-heading"">小技巧</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>{bks_Tips}</p>
<!-- /wp:paragraph -->
";
    var allHtml = htmlIntroduction + htmlStep + HtmlPics + htmlTips;

    // MySQL 数据库连接字符串
    string connectionString = "Server=121.43.51.217;Database=www_legofuns_top;User=root;Password=3afd3666de30b776;";

    // 定义要插入的数据
    int postAuthor = 1;
    string postContent = allHtml;
    string postTitle = "乐高搭建 "+name;
    string postStatus = "publish";
    string guid = "";
    DateTime currentTime = DateTime.Now;

    // 为所有可能为空的字段赋值为空字符串
    string postExcerpt = "";
    string toPing = "";
    string pinged = "";
    string postPassword = "";
    string postContentFiltered = "";
    string postMimeType = "";

    string postName = postTitle; // post_name 赋值为和 postTitle 一样

    // 插入 SQL
    string insertQuery = @"INSERT INTO wp_posts (
            post_author, post_date, post_date_gmt, post_content, post_title, 
            post_status, guid, post_modified, post_modified_gmt, 
            post_excerpt, to_ping, pinged, post_password, post_content_filtered, post_mime_type, post_name
        ) VALUES (
            @postAuthor, @postDate, @postDateGmt, @postContent, @postTitle, 
            @postStatus, @guid, @postModified, @postModifiedGmt, 
            @postExcerpt, @toPing, @pinged, @postPassword, @postContentFiltered, @postMimeType, @postName
        );";

    try
    {
        // 建立数据库连接
        using (MySqlConnection connection = new MySqlConnection(connectionString))
        {
            connection.Open();

            // 创建 MySQL 命令
            using (MySqlCommand command = new MySqlCommand(insertQuery, connection))
            {
                // 添加参数
                command.Parameters.AddWithValue("@postAuthor", postAuthor);
                command.Parameters.AddWithValue("@postDate", currentTime);
                command.Parameters.AddWithValue("@postDateGmt", currentTime.ToUniversalTime());
                command.Parameters.AddWithValue("@postContent", postContent);
                command.Parameters.AddWithValue("@postTitle", postTitle);
                command.Parameters.AddWithValue("@postStatus", postStatus);
                command.Parameters.AddWithValue("@guid", guid);
                command.Parameters.AddWithValue("@postModified", currentTime);
                command.Parameters.AddWithValue("@postModifiedGmt", currentTime.ToUniversalTime());
                command.Parameters.AddWithValue("@postExcerpt", postExcerpt);
                command.Parameters.AddWithValue("@toPing", toPing);
                command.Parameters.AddWithValue("@pinged", pinged);
                command.Parameters.AddWithValue("@postPassword", postPassword);
                command.Parameters.AddWithValue("@postContentFiltered", postContentFiltered);
                command.Parameters.AddWithValue("@postMimeType", postMimeType);
                command.Parameters.AddWithValue("@postName", postName);

                // 执行插入命令
                int rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine($"{rowsAffected} row(s) inserted successfully.");
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: " + ex.Message);
    }

    Console.WriteLine("完成");

}
static async Task<string> Getintroduction(string keyinfo)
{
    // Ollama 服务地址
    string ollamaUrl = "http://112.245.55.15:11434/api/generate";

    // 模型名称
    //string model = "llama3.2-vision:latest";
    string model = "qwen2:7b";


    // 请求内容
    string prompt = keyinfo;

    // 构造请求数据
    var requestData = new
    {
        model = model,
        prompt = prompt
    };

    // 存储完整生成的内容
    string completeResponse = "";

    try
    {
        using (HttpClient client = new HttpClient())
        {
            // 如果需要 API 密钥，设置授权头
            client.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "apiKey"); // 替换为你的真实 API 密钥

            // 将请求数据序列化为 JSON 字符串
            string requestBody = JsonSerializer.Serialize(requestData);

            // 构造 POST 请求
            using (var request = new HttpRequestMessage(HttpMethod.Post, ollamaUrl))
            {
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");

                // 发送请求并接收响应
                HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

                if (response.IsSuccessStatusCode)
                {
                    // 读取流式响应
                    using (var stream = await response.Content.ReadAsStreamAsync())
                    using (var streamReader = new System.IO.StreamReader(stream))
                    {
                        while (!streamReader.EndOfStream)
                        {
                            // 每次读取一行数据
                            string line = await streamReader.ReadLineAsync();

                            if (!string.IsNullOrEmpty(line))
                            {
                                try
                                {
                                    // 解析 JSON 并提取 "response" 字段
                                    var jsonResponse = JsonSerializer.Deserialize<JsonElement>(line);
                                    if (jsonResponse.TryGetProperty("response", out JsonElement responseElement))
                                    {
                                        // 提取生成的内容并累加
                                        string partialResponse = responseElement.GetString();
                                        completeResponse += partialResponse;

                                        // 输出每个新增的字符
                                        Console.Write(partialResponse);
                                    }
                                }
                                catch (JsonException)
                                {
                                    // 忽略非 JSON 格式的行
                                }
                            }
                        }
                    }

                    // 换行并输出最终结果
                    Console.WriteLine("\n生成完成！");
                }
                else
                {
                    Console.WriteLine($"API 调用失败，状态码：{response.StatusCode}");
                    string errorDetails = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"错误详情：{errorDetails}");
                }
            }
        }

        // 最终结果存储在变量 completeResponse 中
        Console.WriteLine($"完整生成结果存储在变量中：{completeResponse}");
        return completeResponse;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"发生错误：{ex.Message}");
        return "error";
    }
}